package com.itheima.reggie.controller;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping(value = "/list",name = "查询地址")
    public ResultInfo list(){
        List<Address> addressList = addressService.findAll();
        return ResultInfo.success(addressList);
    }

    @PostMapping(name = "添加地址")
    public ResultInfo addAddress(@RequestBody Address address){
        addressService.save(address);
        return ResultInfo.success(null);
    }

    @GetMapping(value = "/{id}",name = "根据id查询地址")
    public ResultInfo findById(@PathVariable("id") Long id){
        Address address = addressService.findById(id);
        return ResultInfo.success(address);
    }

    @PutMapping(name = "更新地址")
    public ResultInfo updateAddress(@RequestBody Address address){
        addressService.update(address);
        return ResultInfo.success(null);
    }
    @DeleteMapping(name = "根据id删除地址")
    public ResultInfo delete(Long ids){
        addressService.delete(ids);
        return ResultInfo.success(null);
    }
    @PutMapping(value = "/default",name = "设置默认地址")
    public ResultInfo updateDefault(@RequestBody Address address){
        addressService.updateDefault(address);
        return ResultInfo.success(null);
    }
    @GetMapping(value = "/default",name ="查询当前用户的默认地址")
    public ResultInfo findDefault(){
       Address address=  addressService.findDefault();
       //判断默认地址是否为空
        if (address==null){
            throw new CustomException("您没有设置默认地址");
        }
       return ResultInfo.success(address);
    }
}
